package com.sloan.community.service;

import com.sloan.community.po.User;
import com.sloan.community.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import static com.sloan.community.common.Constant.Sex.UNKNOWN;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class UserService {

    private final UserRepository userRepository;

    public Mono<User> saveOrUpdate(Mono<User> userMono, Integer code) {
        return userMono.flatMap(userInfo -> {
            return userRepository.findByOuth2UserIdAndAuthFrom(String.valueOf(userInfo.getOuth2UserId()), code)
                    .switchIfEmpty(Mono.defer(() -> {
                        User user = new User();
                        user.setSex(UNKNOWN.getCode());
                        user.setAge(0);
                        user.setPhone("");
                        return Mono.just(user);
                    }))
                    .flatMap(dbUser -> {
                        dbUser.setOuth2UserId(String.valueOf(userInfo.getOuth2UserId()));
                        dbUser.setUsername(userInfo.getUsername());
                        dbUser.setNickname(userInfo.getNickname());
                        dbUser.setEmail(userInfo.getEmail());
                        dbUser.setAddress(userInfo.getAddress());
                        dbUser.setAvatarUrl(userInfo.getAvatarUrl());
                        dbUser.setAuthFrom(code);
                        dbUser.setAddress(userInfo.getAddress());
                        return userRepository.save(dbUser);
                    });
        });
    }
}
